//
//  PostViewController.m
//  ECBBusinessCamp
//
//  Created by rimi on 16/6/27.
//  Copyright © 2016年 邓毕华. All rights reserved.
//

#import "PostViewController.h"

#import "RadioButtonsView.h"
#import "CommunityInteractionTableViewCell.h"
#import "CommunityInteractionDetailViewController.h"
#import "InputView.h"

static NSString * const kCommunityInteractionTableViewCellIdentifier = @"communityInteractionTableViewCellIdentifier";

@interface PostViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) RadioButtonsView * radioButtonsView; // 按钮组
@property (nonatomic, strong) UITableView * postTableView; // 帖子表格视图
@property (nonatomic, strong) UILabel * nullLabel; // 没有数据时提示
@property (nonatomic, strong) NSMutableArray * dataSource; // 数据源
@property (nonatomic, strong) NSString * flag; // 活动类型
@property (nonatomic, assign) NSInteger pageNumber; // 起始页数
@property (nonatomic, assign) NSInteger pageSum; // 总页数


@end

@implementation PostViewController

#pragma mark 🌷🌷🌷life cycle🌷🌷🌷
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 添加视图
    [self.view addSubview:self.radioButtonsView];
    [self.view addSubview:self.postTableView];
    [self.view addSubview:self.nullLabel];
    
    // 自动布局
    [_radioButtonsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.sizeOffset(CGSizeMake(SCREEN_WIDTH * 0.08 * 2 + SCREEN_WIDTH * 0.02, SCREEN_WIDTH * 0.08 * 0.5));
        make.top.offset(SCREEN_HEIGHT * 0.12);
        make.left.offset(SCREEN_WIDTH * 0.26);
    }];
    [_postTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_radioButtonsView.mas_bottom).offset(SCREEN_HEIGHT * 0.03);
        make.left.offset(SCREEN_WIDTH * 0.218);
        make.bottom.offset(SCREEN_HEIGHT * -0.09);
        make.right.offset(SCREEN_WIDTH * -0.02);
    }];
    [_nullLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view).offset(SCREEN_WIDTH * 0.195 * 0.5);
        make.centerY.equalTo(self.view);
    }];
    
    // 添加刷新
    [self addRefresh];
}
- (void)viewWillAppear:(BOOL)animated {
    // 首次加载数据
    _pageNumber = 1;
    _flag = @"iOrgnize";
    [self loadData];
}

#pragma mark 🌷🌷🌷UITableViewDataSource🌷🌷🌷
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommunityInteractionTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:kCommunityInteractionTableViewCellIdentifier forIndexPath:indexPath];
    
    // cell 赋值
    [cell.headImageView sd_setImageWithURL:[NSURL URLWithString:BASEURLAPPEND(_dataSource[indexPath.row][@"userPic"])] placeholderImage:[UIImage imageNamed:@"default_head_s.png"]];
    cell.titleLabel.text = _dataSource[indexPath.row][@"title"];
    cell.contentLabel.text = [NSString getEmojiStringForString:_dataSource[indexPath.row][@"desce"]];
    cell.nameLabel.text = [NSString stringWithFormat:@"昵称：%@", _dataSource[indexPath.row][@"nickName"]];
    cell.releaseDateLabel.text = [NSString stringWithFormat:@"发布时间：%@", _dataSource[indexPath.row][@"createTime"]];
    
    return cell;
}

#pragma mark 🌷🌷🌷UITableViewDelegate🌷🌷🌷
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 添加详细视图与控制器
    CommunityInteractionDetailViewController * communityInteractionDetailVc = [[CommunityInteractionDetailViewController alloc] init];
    
    // 属性传值
    communityInteractionDetailVc.id = _dataSource[indexPath.row][@"id"];
    [communityInteractionDetailVc.headImageView sd_setImageWithURL:[NSURL URLWithString:BASEURLAPPEND(_dataSource[indexPath.row][@"userPic"])] placeholderImage:[UIImage imageNamed:@"default_head_s.png"]];
    communityInteractionDetailVc.titleLabel.text = _dataSource[indexPath.row][@"title"];
    communityInteractionDetailVc.contentLabel.text = [NSString getEmojiStringForString:_dataSource[indexPath.row][@"desce"]];
    communityInteractionDetailVc.nameLabel.text = [NSString stringWithFormat:@"昵称：%@", _dataSource[indexPath.row][@"nickName"]];
    InputView * inputView = communityInteractionDetailVc.inputView;
    inputView.inputTextField.text = [NSString stringWithFormat:@"@%@:", _dataSource[indexPath.row][@"nickName"]];
    communityInteractionDetailVc.releaseDateLabel.text = [NSString stringWithFormat:@"发布时间：%@", _dataSource[indexPath.row][@"createTime"]];
    
    
    [self addChildViewController:communityInteractionDetailVc];
    [self.view addSubview:communityInteractionDetailVc.view];
    
    [communityInteractionDetailVc.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.left.offset(SCREEN_WIDTH * 0.195);
        make.bottom.offset(0);
        make.right.offset(0);
    }];
}

#pragma mark 🌷🌷🌷private methods🌷🌷🌷
- (void)addRefresh {
    // 上拉刷新
    _postTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _pageNumber = 0;
        [_dataSource removeAllObjects];
        [self loadData];
    }];
    
    // 下拉加载更多
    _postTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _pageNumber += 1;
        if (_pageNumber > _pageSum) {
            [MBProgressHUD showError:@"没有更多数据"];
            [_postTableView.mj_footer endRefreshing];
            return ;
        }
        [self loadData];
    }];
}
- (void)loadData {
    // POST 参数
    NSMutableDictionary * parramters = [NSMutableDictionary dictionary];
    [parramters setObject:_flag forKey:@"flag"];
    [parramters setObject:[LoginUserInfo defaultUserInfo].userid forKey:@"id"];
    [parramters setObject:@(_pageNumber) forKey:@"pageNum"];
    
    // 加载数据
    [[NetTool sharedTool] requestMethod:POST loadingMsg:@"加载中..." url:BASEURLAPPEND(PERSONALHOMEPAGE_SYSTEMMESSAGE_GETCOMLIST_URL) parameters:parramters finish:^(id responseObject, NSError *error) {
        NSLog(@"%@", responseObject);
        if (!error) {
            if ([responseObject[@"status"] integerValue] == 1) {
                [MBProgressHUD showSuccess:@"加载完成"];
                
                [self.dataSource addObjectsFromArray:responseObject[@"data"]];
                _pageSum = [responseObject[@"totalCount"] integerValue];
                _nullLabel.hidden = _dataSource.count != 0;
                
                // 刷新集合视图
                [_postTableView reloadData];
            } else {
                [MBProgressHUD showError:@"加载失败"];
            }
        } else {
            [MBProgressHUD showError:[[NSString stringWithFormat:@"%@", error] containsString:@"The request timed out."] ? @"登录超时" : @"I don't know"];
        }
        [_postTableView.mj_header endRefreshing];
        [_postTableView.mj_footer endRefreshing];
    }];
}

#pragma mark 🌷🌷🌷getters and setters🌷🌷🌷
- (RadioButtonsView *)radioButtonsView {
    if (!_radioButtonsView) {
        NSArray * buttonNames = @[@"我发起的", @"我参与的"];
        _radioButtonsView = [[RadioButtonsView alloc] initWithNames:buttonNames selectedIndex:^(NSInteger selectIndex) {
            _flag = selectIndex == 0 ? @"iOrgnize" : @"iJoin";
            _pageNumber = 1;
            [_dataSource removeAllObjects];
            [self loadData];
        }];
    }
    return _radioButtonsView;
}
- (UITableView *)postTableView {
    if (!_postTableView) {
        _postTableView = [[UITableView alloc] init];
        
        // 设置数据源
        _postTableView.dataSource = self;
        // 设置代理
        _postTableView.delegate = self;
        // 去除分隔线
        _postTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        // 设置单元格高度
        _postTableView.rowHeight = SCREEN_HEIGHT * 0.26;
        // 注册单元格
        [_postTableView registerClass:[CommunityInteractionTableViewCell class] forCellReuseIdentifier:kCommunityInteractionTableViewCellIdentifier];
    }
    return _postTableView;
}
- (UILabel *)nullLabel {
    if (!_nullLabel) {
        _nullLabel = [[UILabel alloc] init];
        _nullLabel.hidden = YES;
        _nullLabel.text = @"您还没有发布帖子记录哦 @_@";
        _nullLabel.font = [UIFont systemFontOfSize:20];
        _nullLabel.textColor = RGB_COLOR(53, 181, 222, 1);
    }
    return _nullLabel;
}
- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

@end
